import { get } from 'svelte/store';
import { persistentWritable } from './persist';

type Persistent<T> = {
	data: T | null;
	time: number;
};

const getDefaultValue = () => ({ data: null, time: new Date().getTime() });

export function getPersistent<T>(key: string, overtime: number = 1000 * 60 * 60 * 24) {
	const result = persistentWritable<Persistent<T>>(key, getDefaultValue());
	const { data, time } = get(result);

	if (new Date().getTime() - time > overtime) {
		result.update(getDefaultValue);
		return null;
	}

	return data;
}

export function setPersistent<T>(key: string, value: T) {
	const result = persistentWritable<Persistent<T>>(key, getDefaultValue());
	result.update((data) => ({ ...data, data: value, time: new Date().getTime() }));
}
